package com.azt.provider.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.azt.api.pojo.Channel;
import com.azt.api.service.ChannelService;
import com.azt.model.easy.EasyTree;
import com.azt.model.easy.EasyTreeModel;
import com.azt.provider.mapper.ChannelMapper;
import com.azt.service.EasyService;

import tk.mybatis.mapper.entity.Example;

@Service
@Transactional
public class ChannelServiceImpl implements ChannelService {
	
	@Autowired
	private ChannelMapper cm;

	@Autowired
	private EasyService es;

	@Override
	public List<EasyTree> getChannelTree() {
		
//		Example exp = new Example(Channel.class);
//		exp.createCriteria().andEqualTo("parentId", 0);
//		List<Channel> listByParams = cm.selectByExample(exp);
		List<Channel> listByParams = cm.getTreeByPid(0);
		if(!listByParams.isEmpty()){
			setChildren(listByParams);
		}
		EasyTreeModel comboTreeModel = new EasyTreeModel("id", "channelName", "children");
		comboTreeModel.setCodeField("code");
		return es.easyTree(listByParams, comboTreeModel, null, true , true);

	}
	
	private void setChildren(List<Channel> channels){
		//if(!channels.isEmpty()){
			for(Channel c : channels){
				List<Channel> children = cm.getTreeByPid(c.getId());
				if(!children.isEmpty()){
					c.setChildren(children);
					setChildren(children);
				}
			}
		//}
	}


	@Override
	public Channel getChannelById(Integer id) {
		return cm.selectByPrimaryKey(id);
	}

	@Override
	public void saveOrUpdate(Channel channel) {
		if(channel.getId() == null) cm.insert(channel);
		else cm.updateByPrimaryKey(channel);
	}

	@Override
	public void deleteAllEntitie(Integer pid) {
		cm.deleteByParentId(pid);
		cm.deleteByPrimaryKey(pid);
	}

	@Override
	public List<Channel> getChannelListByParentCode(String code) {
		return cm.getChannelListByParentCode(code);
	}

	@Override
	public Channel getChannelByCode(String code) {
		Channel c=new Channel();
		c.setCode(code);
		return cm.selectOne(c);
	}

	@Override
	public List<Channel> getChannelListByCodesArr(String[] codesArr) {
		List<Channel> channelList=new ArrayList<>();
		for(String code:codesArr){
			Channel c=new Channel();
			c.setCode(code);
			channelList.add(cm.selectOne(c));
		}
		return channelList;
	}
}
